package com.shanlitech.et.controller;

import com.shanlitech.et.bean.RetData;
import com.shanlitech.et.mapper.SpeechRecordMapper;
import com.shanlitech.et.model.SpeechRecord;
import com.shanlitech.et.utils.ByteUtils;
import com.shanlitech.et.utils.HttpClientUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class StoreController {
    private final Logger logger= LoggerFactory.getLogger(this.getClass());
    @Resource
    private SpeechRecordMapper speechRecordMapper;

    @RequestMapping("insert")
    @ResponseBody
    public void insert(SpeechRecord record) {
        logger.info("insert收到参数:" + record);
        speechRecordMapper.insertSelective(record);
    }

    @RequestMapping("update")
    @ResponseBody
    public void update(SpeechRecord record) {
        logger.info("update收到参数:" + record);
        speechRecordMapper.updateByPrimaryKeySelective(record);
    }

    @RequestMapping("findByGid")
    @ResponseBody
    public Object findByGid(String gid, String time, String count) {
        logger.info("根据gid查询讲话记录" + gid);
        RetData ret = new RetData();
        if(!StringUtils.hasText(gid)) {
            ret.setRet(-1);
            ret.setMsg("gid为空");
            return ret;
        }
        if(!StringUtils.hasText(time)) {
            time = System.currentTimeMillis() + "";
        }
        if(!StringUtils.hasText(count)) {
            count = "3";
        }
        List<SpeechRecord> records = speechRecordMapper.findByGidAndtStartLess(Long.parseLong(gid), Long.parseLong(time), Integer.parseInt(count));
        ret.setData(records);
        return ret;
    }

    @RequestMapping("findByGids")
    @ResponseBody
    public Object findByGids(Long[] gids, String time, String count) {
        RetData ret = new RetData();
        if(gids == null || !StringUtils.hasText(time) || !StringUtils.hasText(count)) {
            ret.setRet(-1);
            ret.setMsg("参数为空");
            return ret;
        }
        List<SpeechRecord> records = speechRecordMapper.findByGidsAndtStartLess(gids, Long.parseLong(time), Integer.parseInt(count));
        ret.setData(records);
        return ret;
    }

    @RequestMapping("findBySpeechId")
    @ResponseBody
    public Object findBySpeechId(String speechId, HttpServletResponse response) {
        logger.info("根据speechId查询讲话记录" + speechId);
        RetData ret = new RetData();
        if(!StringUtils.hasText(speechId)) {
            ret.setRet(-1);
            ret.setMsg("参数为空");
            return ret;
        }
        SpeechRecord speechRecord = speechRecordMapper.selectByPrimaryKey(Long.parseLong(speechId));
        if(speechRecord != null && StringUtils.hasText(speechRecord.getSpeech_index())) {
            //根据文件索引去下载文件
            BufferedReader in = null;
            try {
                HttpClient client = HttpClientUtils.createSSLClientDefault();
                HttpGet request = new HttpGet();
                request.setURI(new URI(speechRecord.getSpeech_index()));

                //设置参数
                HttpResponse httpResponse = client.execute(request);
                int code = httpResponse.getStatusLine().getStatusCode();
                if(code == HttpStatus.SC_OK) {
                    byte[] result = EntityUtils.toByteArray(httpResponse.getEntity());
                    logger.info("下载的文件路径" + speechRecord.getSpeech_index() + "\n下载的文件内容:" + ByteUtils.toHexString(result));
                    response.setContentType("application/octet-stream;charset=utf-8");
                    String filenamedisplay = speechId;
                    filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
                    response.addHeader("Content-Disposition", "attachment;filename="
                            + filenamedisplay + ".hex");
                    OutputStream os= response.getOutputStream();
                    os.write(result);
                    os.flush();
                    os.close();
                } else {
                    ret.setRet(-3);
                    ret.setMsg("语音文件下载错误" + code);
                    return ret;
                }
            } catch (Exception e) {
                logger.error("下载语音文件错误, speechId=" + speechId, e);
                ret.setRet(-3);
                ret.setMsg("语音文件下载错误");
                return ret;
            }

            return ret;
        } else {
            ret.setRet(-2);
            ret.setMsg("没有该条记录，或该语音记录未完成");
            return ret;
        }
    }
}
